package com.saui.traceu.controller;

import android.location.Location;

import com.saui.traceu.model.TraceDBAdapter;
import com.saui.traceu.model.TracePoint;

public class TraceCache {

	private final int MAX_CACHE_SIZE = 200;
	private Location[] locationCache = new Location[MAX_CACHE_SIZE];
	private int sentinel = 0;
	private TraceDBAdapter mDb;
	private SessionManager sessionManager;
//	private boolean writing = false;

	private static TraceCache instance;

	private TraceCache(TraceDBAdapter dba, SessionManager sm) {
		mDb = dba;
		sessionManager = sm;
	}

	public static TraceCache getTraceCache(TraceDBAdapter dba, SessionManager sm) {
		if (instance == null) {
			instance = new TraceCache(dba,sm);
		}
		return instance;
	}


	public synchronized void writePointsToDb(long sessionID) {
		Location[] oldLocationCache;
		int oldSize;
		TracePoint[] tps;
		synchronized(this){
		//	writing = true;
			oldLocationCache = locationCache;
			locationCache = new Location[MAX_CACHE_SIZE];
			oldSize = sentinel;
			sentinel = 0;
			tps= new TracePoint[oldSize];
		}

		for (int i = 0; i < oldSize; i++) {
			Location l = oldLocationCache[i];

			double lat = l.getLatitude();
			double lon = l.getLongitude();

			TracePoint newPoint = new TracePoint();
			newPoint.setSessionId(sessionManager.getCurrentSession().getId());
			newPoint.setLatitude(lat);
			newPoint.setLongitude(lon);
			tps[i] = newPoint;
		}
		
		mDb.createTracePoints(tps);
	}

	public void cacheLocation(Location tp) {
		if (sentinel < MAX_CACHE_SIZE) {
			synchronized(this) {
				locationCache[sentinel] = tp;
				sentinel++;
			}
		} else {
			new Thread(new Runnable() {
				public void run() {
					writePointsToDb(sessionManager.getCurrentSession().getId());
				}
			}).start();
		}
	}
}
